package com.practice.service.impl.user;

import com.practice.dao.user.UserDao;
import com.practice.domain.user.User;
import com.practice.exception.PracticeException;
import com.practice.service.impl.BaseServiceImpl;
import com.practice.service.user.UserService;
import com.practice.util.PasswordUtil;
import com.practice.util.RegexUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Administrator on 2016/8/20.
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, transactionManager = "txManager")
public class UserServiceImpl extends BaseServiceImpl implements UserService {
  @Autowired
  private UserDao userDao;

  public User detail(final Long id) throws PracticeException {
    return detail(id, userDao, "用户");
  }

  public User findByEmail(String email) throws PracticeException {
    validateEmail(email);
    return userDao.findByEmail(email);
  }

  public void checkEmail(String email) throws PracticeException {
    User user = findByEmail(email);
    if (null != user) {
      throw new PracticeException("邮箱已被注册！");
    }
  }

  public User findByUsername(String username) throws PracticeException {
    validateEmpty(username, "用户名");
    return userDao.findByUsername(username);
  }

  public void checkUsername(String username) throws PracticeException {
    User user = findByUsername(username);
    if (null != user) {
      throw new PracticeException("用户名已存在！");
    }
  }

  public User create(final String username, final String email, final String password, final String confirmPassword) throws PracticeException {
    validateUsernameExist(username);
    validateEmailExist(email);
    validateEmpty(password, "密码");
    if (!password.equals(confirmPassword)) {
      throw new PracticeException("两次输入密码不正确，请重新输入！");
    }
    return userDao.create(username, email, PasswordUtil.encode(password));
  }

  private void validateEmailExist(String email) throws PracticeException {
    validateEmail(email);
    User user = findByEmail(email);
    if (null != user) {
      throw new PracticeException("该邮箱已注册！");
    }
  }

  private void validateEmail(String email) throws PracticeException {
    validateEmpty(email, "邮箱");
    if (!RegexUtil.checkEmail(email)) {
      throw new PracticeException("邮箱格式不正确！");
    }
  }

  private void validateUsernameExist(String username) throws PracticeException {
    validateEmpty(username, "用户名");
    User user = findByUsername(username);
    if (null != user) {
      throw new PracticeException("用户名已存在");
    }
  }
}
